// 引入工具函数
const util = require('../../utils/util.js');
const app = getApp();

Page({
  data: {
    totalRecords: 0,
    thisMonthRecords: 0,
    favoriteShop: '暂无',
    topTeas: [],
    // 存储饼图数据，用于交互
    pieChartData: {
      typeChart: { items: [], total: 0 },
      sugarChart: { items: [], total: 0 },
      iceChart: { items: [], total: 0 }
    },
    // 当前悬浮的饼图切片
    activeSlice: {
      typeChart: -1,
      sugarChart: -1,
      iceChart: -1
    }
  },

  onLoad: function (options) {
    this.getStatistics();
  },

  onShow: function () {
    // 页面显示时刷新数据
    this.getStatistics();
  },

  // 分享给好友
  onShareAppMessage() {
    return {
      title: `我的奶茶统计：共${this.data.totalRecords}杯，最爱${this.data.favoriteShop}`,
      path: '/pages/statistics/statistics',
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: `我的奶茶数据分析：本月已喝${this.data.thisMonthRecords}杯，最爱${this.data.favoriteShop}`,
      query: 'from=timeline',
    };
  },

  getStatistics: function () {
    const that = this;
    
    // 获取本地存储的奶茶记录
    wx.getStorage({
      key: 'teaRecords',
      success(res) {
        const records = res.data || [];
        
        if (records.length === 0) {
          that.setData({
            totalRecords: 0,
            thisMonthRecords: 0,
            favoriteShop: '暂无',
            topTeas: []
          });
          
          // 绘制空饼图
          that.drawEmptyCharts();
          return;
        }
        
        // 计算总记录数
        const totalRecords = records.length;
        
        // 计算本月记录
        const now = new Date();
        const currentMonth = now.getMonth();
        const currentYear = now.getFullYear();
        
        const thisMonthRecords = records.filter(record => {
          const recordDate = new Date(record.date);
          return recordDate.getMonth() === currentMonth && 
                 recordDate.getFullYear() === currentYear;
        }).length;
        
        // 计算最喜爱的店铺
        const shopCount = {};
        records.forEach(record => {
          if (record.shop) {
            shopCount[record.shop] = (shopCount[record.shop] || 0) + 1;
          }
        });
        
        let favoriteShop = '暂无';
        let maxCount = 0;
        for (const shop in shopCount) {
          if (shopCount[shop] > maxCount) {
            maxCount = shopCount[shop];
            favoriteShop = shop;
          }
        }
        
        // 计算最爱奶茶排行
        const teaCount = {};
        records.forEach(record => {
          const key = `${record.name}-${record.shop}`;
          teaCount[key] = (teaCount[key] || 0) + 1;
          teaCount[key + '_data'] = record;
        });
        
        const topTeas = [];
        for (const key in teaCount) {
          if (!key.endsWith('_data')) {
            const count = teaCount[key];
            const data = teaCount[key + '_data'];
            topTeas.push({
              name: data.name,
              shop: data.shop,
              count: count
            });
          }
        }
        
        topTeas.sort((a, b) => b.count - a.count);
        const finalTopTeas = topTeas.slice(0, 5); // 取前5个
        
        that.setData({
          totalRecords,
          thisMonthRecords,
          favoriteShop,
          topTeas: finalTopTeas
        });
        
        // 统计不同分类的数据
        that.analyzeAndDrawCharts(records);
      },
      fail() {
        that.setData({
          totalRecords: 0,
          thisMonthRecords: 0,
          favoriteShop: '暂无',
          topTeas: []
        });
        
        // 绘制空饼图
        that.drawEmptyCharts();
      }
    });
  },
  
  analyzeAndDrawCharts: function(records) {
    // 统计奶茶类型
    const typeCount = {};
    records.forEach(record => {
      if (record.type) {
        typeCount[record.type] = (typeCount[record.type] || 0) + 1;
      }
    });
    
    // 统计糖度偏好
    const sugarCount = {};
    records.forEach(record => {
      if (record.sugar) {
        sugarCount[record.sugar] = (sugarCount[record.sugar] || 0) + 1;
      }
    });
    
    // 统计冰量偏好
    const iceCount = {};
    records.forEach(record => {
      if (record.ice) {
        iceCount[record.ice] = (iceCount[record.ice] || 0) + 1;
      }
    });
    
    // 绘制饼图
    this.drawPieChart('typeChart', typeCount, '类型');
    this.drawPieChart('sugarChart', sugarCount, '糖度');
    this.drawPieChart('iceChart', iceCount, '冰量');
    
    // 为每个饼图设置触摸事件
    this.setupTouchEvents();
  },
  
  setupTouchEvents: function() {
    // 为每个饼图设置触摸事件
    const charts = ['typeChart', 'sugarChart', 'iceChart'];
    const that = this;
    
    charts.forEach(chartId => {
      // 获取canvas元素信息
      wx.createSelectorQuery()
        .select(`#${chartId}`)
        .boundingClientRect(function(rect) {
          if (rect) {
            const chartData = that.data.pieChartData[chartId];
            
            // 设置事件处理器
            that.setupTouchHandler(chartId, rect, chartData);
          }
        })
        .exec();
    });
  },
  
  setupTouchHandler: function(chartId, rect, chartData) {
    const canvasWidth = 300; // 画布宽度
    const canvasHeight = 200; // 画布高度
    const radius = 80; // 饼图半径
    const centerX = canvasWidth / 2;
    const centerY = canvasHeight / 2;
    const that = this;
    
    // 创建touch事件处理器
    const touchHandler = function(e) {
      const touch = e.touches[0];
      
      // 计算触摸点相对于画布的坐标
      const x = touch.pageX - rect.left;
      const y = touch.pageY - rect.top;
      
      // 计算触摸点与圆心的距离
      const distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
      
      // 如果触摸点在饼图内
      if (distance <= radius) {
        // 计算触摸点的角度
        let angle = Math.atan2(y - centerY, x - centerX);
        if (angle < 0) {
          angle += 2 * Math.PI;
        }
        
        // 找出触摸的是哪个切片
        let startAngle = 0;
        for (let i = 0; i < chartData.items.length; i++) {
          const item = chartData.items[i];
          const sliceAngle = 2 * Math.PI * item.value / chartData.total;
          
          if (angle >= startAngle && angle <= startAngle + sliceAngle) {
            // 如果是新的切片，则更新状态并重绘
            if (that.data.activeSlice[chartId] !== i) {
              const activeSlice = { ...that.data.activeSlice };
              activeSlice[chartId] = i;
              that.setData({ activeSlice });
              
              // 重绘突出显示的切片
              that.drawPieChart(chartId, null, null, i);
            }
            break;
          }
          
          startAngle += sliceAngle;
        }
      } else {
        // 如果触摸点在饼图外，取消突出显示
        if (that.data.activeSlice[chartId] !== -1) {
          const activeSlice = { ...that.data.activeSlice };
          activeSlice[chartId] = -1;
          that.setData({ activeSlice });
          
          // 重绘正常状态
          that.drawPieChart(chartId, null, null, -1);
        }
      }
    };
    
    // 添加事件监听
    this.addTouchEvents(chartId, touchHandler);
  },
  
  addTouchEvents: function(chartId, handler) {
    // 获取canvas元素
    const query = wx.createSelectorQuery();
    query.select(`#${chartId}`)
      .fields({ node: true, size: true })
      .exec((res) => {
        if (res[0]) {
          const canvas = res[0].node;
          
          // 添加touchmove事件监听
          canvas.addEventListener('touchmove', handler);
          
          // touchend时取消突出显示
          canvas.addEventListener('touchend', () => {
            const activeSlice = { ...this.data.activeSlice };
            activeSlice[chartId] = -1;
            this.setData({ activeSlice });
            
            // 重绘正常状态
            this.drawPieChart(chartId, null, null, -1);
          });
        }
      });
  },
  
  drawPieChart: function(canvasId, data, title, activeIndex = -1) {
    const ctx = wx.createCanvasContext(canvasId);
    const canvasWidth = 300; // 画布宽度
    const canvasHeight = 200; // 画布高度
    const radius = 80; // 饼图半径
    const centerX = canvasWidth / 2;
    const centerY = canvasHeight / 2;
    
    // 设置暖色系颜色方案，替换默认的蓝色系
    const colors = ['#FF9500', '#FFCC00', '#FF6B6B', '#C3A368', '#E6C9A8', '#D4A373', '#8B5A2B', '#A67F5D', '#DDC3A5'];
    
    // 绘制背景
    ctx.setFillStyle('#FCFAF7');
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
    
    // 如果没有传入数据，使用已存储的数据（用于重绘）
    let items = [];
    let total = 0;
    
    if (data) {
      // 准备数据
      items = [];
      for (const label in data) {
        items.push({
          label: label,
          value: data[label]
        });
      }
      
      // 计算总和
      total = items.reduce((sum, item) => sum + item.value, 0);
      
      // 排序数据（可选）
      items.sort((a, b) => b.value - a.value);
      
      // 存储数据以供后续交互使用
      const pieChartData = { ...this.data.pieChartData };
      pieChartData[canvasId] = { items, total };
      this.setData({ pieChartData });
    } else {
      // 使用已存储的数据
      const storedData = this.data.pieChartData[canvasId];
      items = storedData.items;
      total = storedData.total;
    }
    
    // 绘制饼图
    let startAngle = 0;
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      const sliceAngle = 2 * Math.PI * item.value / total;
      
      // 设置填充颜色
      ctx.setFillStyle(colors[i % colors.length]);
      
      // 检查是否是活动切片
      const isActive = (i === activeIndex);
      
      // 绘制扇形
      ctx.beginPath();
      ctx.moveTo(centerX, centerY);
      
      // 如果是活动切片，将其略微突出
      const sliceRadius = isActive ? radius * 1.08 : radius;
      ctx.arc(centerX, centerY, sliceRadius, startAngle, startAngle + sliceAngle);
      ctx.closePath();
      ctx.fill();
      
      // 如果是活动切片，添加阴影效果
      if (isActive) {
        ctx.setShadow(0, 0, 10, 'rgba(0, 0, 0, 0.3)');
      }
      
      // 保存当前角度用于绘制标签
      const midAngle = startAngle + sliceAngle / 2;
      
      // 绘制标签连线和文本
      const labelRadius = radius * 1.2;
      const labelX = centerX + labelRadius * Math.cos(midAngle);
      const labelY = centerY + labelRadius * Math.sin(midAngle);
      
      ctx.setFillStyle('#333333');
      ctx.setShadow(0, 0, 0, 'rgba(0, 0, 0, 0)'); // 清除阴影
      ctx.setFontSize(10);
      
      // 计算百分比
      const percentage = Math.round(item.value / total * 100);
      // 只绘制大于等于5%的标签或活动切片的标签
      if (percentage >= 5 || isActive) {
        const labelText = `${item.label} ${percentage}%`;
        const labelWidth = ctx.measureText(labelText).width || 30; // fallback width
        
        if (isActive) {
          // 为活动切片添加突出标签
          ctx.setFontSize(12);
          ctx.setFillStyle('#FF6B00');
          ctx.setTextAlign('center');
          
          // 绘制带有背景的标签
          const padding = 5;
          const bgX = labelX - labelWidth / 2 - padding;
          const bgY = labelY - 10 - padding; // 10 is approximate font height
          const bgWidth = labelWidth + padding * 2;
          const bgHeight = 20 + padding * 2;
          
          ctx.setFillStyle('rgba(255, 255, 255, 0.9)');
          ctx.fillRect(bgX, bgY, bgWidth, bgHeight);
          
          ctx.setFillStyle('#FF6B00');
          ctx.fillText(labelText, labelX, labelY);
        } else {
          // 普通标签
          ctx.fillText(labelText, labelX - 20, labelY);
        }
      }
      
      // 更新起始角度
      startAngle += sliceAngle;
    }
    
    // 绘制标题
    ctx.setFillStyle('#333333');
    ctx.setFontSize(14);
    
    // 绘制到画布
    ctx.draw();
  },
  
  drawEmptyCharts: function() {
    // 绘制空的饼图提示用户没有数据
    const drawEmpty = (canvasId, text) => {
      const ctx = wx.createCanvasContext(canvasId);
      const canvasWidth = 300;
      const canvasHeight = 200;
      
      // 设置背景
      ctx.setFillStyle('#FCFAF7');
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);
      
      // 绘制提示文本
      ctx.setFillStyle('#999999');
      ctx.setFontSize(14);
      ctx.setTextAlign('center');
      ctx.setTextBaseline('middle');
      ctx.fillText(text, canvasWidth/2, canvasHeight/2);
      
      ctx.draw();
    };
    
    drawEmpty('typeChart', '暂无奶茶类型数据');
    drawEmpty('sugarChart', '暂无糖度偏好数据');
    drawEmpty('iceChart', '暂无冰量偏好数据');
  }
}); 